package cn.com.isfree.tio.client.handler;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.utils.json.Json;

import cn.com.isfree.db.config.InitConfig;
import cn.com.isfree.db.task.CommonJob;
import cn.com.isfree.tio.common.ShowcasePacket;
import cn.com.isfree.tio.common.ShowcaseSessionContext;
import cn.com.isfree.tio.common.Type;
import cn.com.isfree.tio.common.intf.AbsShowcaseBsHandler;
import cn.com.isfree.tio.common.packets.SyncReqBody;
import cn.com.isfree.tio.common.packets.SyncRespBody;

/**
 * @author tanyaowu
 * 2017年3月27日 下午9:51:28
 */
public class SyncReqHandler extends AbsShowcaseBsHandler<SyncReqBody> {
	private static Logger log = LoggerFactory.getLogger(SyncReqHandler.class);

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}

	/**
	 *
	 * @author tanyaowu
	 */
	public SyncReqHandler(){
		
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<SyncReqBody> bodyClass() {
		return SyncReqBody.class;
	}

	/**
	 * @param packet
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(ShowcasePacket packet, SyncReqBody bsBody, ChannelContext channelContext) throws Exception {
		if(bsBody.getSynSeq()!=null&&bsBody.getSynSeq()>0) {
			log.info("收到点对点同步请求消息:{}", Json.toJson(bsBody));
			ShowcaseSessionContext showcaseSessionContext = (ShowcaseSessionContext) channelContext.getAttribute();
			SyncRespBody syncRespBody = new SyncRespBody();
			syncRespBody.setFromUserid(showcaseSessionContext.getUserid());
			syncRespBody.setText(bsBody.getText());
			syncRespBody.setSynSeq(bsBody.getSynSeq());
			ShowcasePacket respPacket = new ShowcasePacket();
			respPacket.setSynSeq(bsBody.getSynSeq());
			respPacket.setType(Type.SYNC_MSG_RESP);
			respPacket.setBody(Json.toJson(syncRespBody).getBytes(ShowcasePacket.CHARSET));
			Aio.send(channelContext,respPacket);
			Scheduler scheduler = InitConfig.factory.getScheduler();
			switch (bsBody.getText()) {
			case "stop":
				try {
					TriggerKey triggerKey = TriggerKey.triggerKey("TriggerName=trigger_name1",
							"TriggerGroupName=trigger_group_name1");
					scheduler.pauseTrigger(triggerKey);// 停止触发器
					scheduler.pauseTrigger(triggerKey);// 移除触发器
					JobKey jobKey = JobKey.jobKey("JobName=job_name1","JobGroupName=job_group_name1");
					scheduler.deleteJob(jobKey);// 删除任务
				}catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case "start":
				try {
					TriggerKey triggerKey = TriggerKey.triggerKey("TriggerName=trigger_name1",
							"TriggerGroupName=trigger_group_name1");
					CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
					if(trigger==null) {
						// 不存在，创建一个
						JobDetail jobDetail = (JobDetail) JobBuilder.newJob(CommonJob.class)
								.withIdentity("JobName=job_name"+1,"JobGroupName=job_group_name"+1).build();
						jobDetail.getJobDataMap().put("test", "-当前是执行：job"+1);
						// 表达式调度构建器
						CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/"+5+" * * * * ?");
						// 按新的cronExpression表达式构建一个新的trigger
						trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
						scheduler.scheduleJob(jobDetail, trigger);
						scheduler.start();
					}else {
						// Trigger已存在，那么更新相应的定时设置
						// 表达式调度构建器
						CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/"+5+" * * * * ?");
						// 按新的cronExpression表达式重新构建trigger
						trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
						// 按新的trigger重新设置job执行
						scheduler.rescheduleJob(triggerKey, trigger);
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		}else {
			throw new RuntimeException("synSeq必须大于0");
		}
		return null;
	}
}
